import re

from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import reqparse
from util.myjwt import myjwt
from util.captcha.captcha import captcha
import json, random, time, requests
from util.myredis import r
from util.smssdk import send_message
from models.user import *

user_blue = Blueprint("userblue",__name__)


@user_blue.route("/getImageCode")
def getImageCode():
    # 生成图片验证码 text文字   image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid做为redis key
    uuid = request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid, text, 300)
    # 以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = 'image/jpg'
    return res

@user_blue.route('/sendsms',methods=['POST'])
def sms():
    data = request.data
    if data:
        data = json.loads(data)
        mobile = data['mobile']
        uuid = data['uuid']
        imagecode = data['imagecode']
        # 获取图片验证码
        code = r.str_get(uuid)
        if code:
            if imagecode.lower() != code.decode().lower():
                return jsonify({'code':10200,'msg':'验证码有误'})
            # 获取之后删除图片验证码
            r.del_key(uuid)
        else:
            return jsonify({'code':10201,'msg':'图片验证码不存在'})
        if not re.findall(r'^1[3-9]\d{9}$',mobile):
            return jsonify({'code':10023,'msg':'手机号格式有误'})
        v = r.str_get(mobile)
        if v:
            return jsonify({'code':10202,'msg':'一分钟只能发送一次'})
        c = send_message(mobile)
        print(c)
        return jsonify({'code':200,'msg':'发送成功'})
@user_blue.route('/login',methods=['POST'])
def login():
    data = request.data

    if data:
        data = json.loads(data)
        mobile = data['mobile']
        sms = data['sms']
        smscode = r.str_get(mobile)
        if smscode:
            if smscode.decode() != sms:
                return jsonify({'code':10022,'msg':'验证码有误'})
            user = User.query.filter_by(mobile=mobile).first()
            if user:
                token = myjwt.jwt_encode({'data':{'userid':user.id,'mobile':user.mobile},'exp':int(time.time())})
                return jsonify({'code':200,'msg':'登录成功','token':token,'userid':user.id})
            else:
                create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                user = User(mobile=mobile,create_time=create_time)
                db.session.add(user)
                db.session.commit()
                return jsonify({'code':201,'msg':'注册成功'})

        else:
            return jsonify({'code':10200,'msg':'验证码过期'})
    else:
        return jsonify({'code': 10200, 'msg': '请输入账号'})

@user_blue.route('/wblogin')
def wblogin():
    client_id = '3674019597'
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({'code':200,'url':url})
@user_blue.route('/user/weiboCallback/')
def wbcallback():
    req = reqparse.RequestParser()
    req.add_argument('code')
    args =req.parse_args()
    code = args['code']
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    sflogin = db.session.execute("select * from user u inner join sflogin s on u.id = s.userid where s.uid=%s"%(uid))
    sf = list(sflogin)
    # 获取的数据是个转换成list，里面的数据是值，根据索引获取
    if sf:
        for i in sf:
            token = myjwt.jwt_encode(data={'data':{'uid':i[0],'exp':int(time.time())}})
            return redirect("http://localhost:8080/updatetoken?token=" + token + "&userid=" + str(i[0]))
    else:
        return redirect("http://localhost:8080/bingmobile?token=" + str(token) + "&uid=" + str(uid))

@user_blue.route('/bingmobile',methods=['POST'])
def bingmobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    try:
        user = User(mobile=mobile)
        db.session.add(user)
        db.session.commit()
        uid = data['uid']
        token = data['token']
        # users= User.query.filter_by(mobile=mobile).first()
        # print(users)
        sf = sf_login(uid=uid,token=token,webfrom='微博',userid=int(user.id))
        db.session.add(sf)
        db.session.commit()
    except:
        return jsonify({'code':10020,'msg':'擦'})

    token = myjwt.jwt_encode(data={'data':{'uid':user.id,'exp':int(time.time())}})
    return jsonify({'code':200,'token':token,'userid':user.id})



# 权限验证
def pomition():
    def is_login(func):
        def wrapper(self,*args,**kargs):
            #业务
            #获取token
            headers = self.request.headers
            try:
                token = headers['token']
                flag = myjwt.check(token)
                if flag == True:
                    #解析验证时间
                    payload = myjwt.jwt_decode(token)
                    ptime = payload['data']['exp']
                    now = time.time()
                    if int(now)-int(ptime)>3600:
                         return  self.finish({"code":402})
                    #  {"data": {"name": "zs", "userid": 1,'exp':}}
                else:
                     self.finish({"code":403})
            except:
                 self.finish({"code":401})
            #验证token
            # headers['token']
            #解析获取时间和当前时间对比
            func(self,*args,**kargs)
        return wrapper
    return is_login


# 退出登录
@user_blue.route("/exitlogin")
def loginout():
    key = 'loginoutlist'
    token = request.headers['Token']
    print(token)
    r.sortedset_add(key,token,int(time.time()))
    return jsonify({'code':200,'msg':'退出成功'})








# @user_blue.route("/login",methods=["POST"])
# # 注册登录
# def login():
#     data = json.loads(request.data)
#     mobile = data["mobile"]
#     pwd = data["pwd"]
#     if not all([mobile,pwd]):
#         return jsonify({"code": 400,"msg":"字段不能为空"})
#     admin = Admin_User.query.filter_by(mobile=mobile).first()
#
#     if admin:
#         if admin.password != pwd:
#             return jsonify({"code": 400, "msg": "密码错误"})
#         # 获取页面权限
#         menulist,myurl = getMenu(admin.role_id)
#         print("页面权限>>>",menulist,'接口权限>>>',myurl)
#         list = GetResourceurl(admin.role_id)
#         data = {"data": {"userid": admin.id, "mobile": admin.mobile,'role_id':admin.role_id, "exp": int(time.time())}}
#         key = 'role_id' + str(data['data']['role_id'])
#         r.str_add(key,json.dumps(list))
#         token = myjwt.jwt_encode(data)
#         return jsonify({"code": 200, "msg": "登录成功","token":token,"mobile":admin.mobile,"user_id":admin.id,"data":menulist,"myurl":myurl,'role_id':admin.role_id})
#     user = Admin_User(mobile=mobile,password=pwd,role_id=1)
#     db.session.add(user)
#     db.session.commit()
#     return jsonify({"code": 201, "msg": "注册成功"})
#
# # 页面权限
# def getMenu(roleid):
#     role = db.session.execute("select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resource_id=res.id  inner join resource as pres on res.pid=pres.id where rr.role_id=%d and res.type=1 and button_id=4"%int(roleid))
#     if role:
#         reslist = []
#         ids = []
#         myurl = []
#         for i in role:
#             myurl.append(i['url'])
#             # 判断父类是否存在，不存在添加
#             if i["pid"] not in ids:
#                 ids.append(i['pid'])
#                 reslist.append(
#                     {"id": i["pid"], "name": i['pname'], "son": [{"id": i['id'], "name": i['name'], 'url': i['url']}]})
#             else:
#                 # 存在，查找父类，遍历父类用子类的pid对比
#                 for (index, p) in enumerate(reslist):
#                     if i['pid'] == p['id']:
#                         # 将子类加到父类下
#                         reslist[index]['son'].append({"id": i['id'], "name": i['name'], 'url': i['url']})
#         return reslist, myurl
#
#
# def GetResourceurl(role_id):
#     sql = db.session.execute("""select res.url from role_resource as rr left join resource as res on rr.resource_id=res.id where rr.role_id=%d and type=2"""%int(role_id))
#     list = []
#     for i in sql:
#         list.append(i.url)
#     return list
